package ch.cm.android.teamlearn.framents;

import java.sql.SQLException;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import ch.cm.android.teamlearn.R;
import ch.cm.android.teamlearn.learnactivity.LeanActivity;
import ch.cm.android.teamlearn.model.Question;
import ch.cm.android.teamlearn.orm.DataBaseHelper;

import com.j256.ormlite.dao.Dao;

public class QuestionChooseFragment extends Fragment{
    
    private LinearLayout linearLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_choose_question, container, false);
        return root;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        linearLayout = (LinearLayout) getActivity().findViewById(R.id.ll_learnbuttons);
        List<Question> questions = null;
        try {
            Dao<Question, Integer> dao = new DataBaseHelper(getActivity()).getDao();
            questions = dao.query(dao.queryBuilder().groupBy("tag").prepare());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        for (Question question : questions) {
            Button button = new Button(getActivity());
            button.setOnClickListener(new ChooseListener(question.tag));
            button.setText(question.tag);
            linearLayout.addView(button);
        }
    }
    
    @Override
    public void onPause() {
        linearLayout.removeAllViews();
        super.onPause();
    }
    
    private class ChooseListener implements OnClickListener{
        
        private String tag = "";
        
        public ChooseListener(String tag){
            this.tag = tag;
        }

        @Override
        public void onClick(View v) {
            
            if (!(tag.equals(""))) {
                Intent intent = new Intent(QuestionChooseFragment.this.getActivity(), LeanActivity.class);
                intent.putExtra("tag",tag);
                startActivity(intent);
            }else {
                Toast.makeText(QuestionChooseFragment.this.getActivity(), "No Tag",Toast.LENGTH_SHORT).show();
            }
        }
        
    }
}
